from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from django.http import HttpResponseRedirect
from .models import New, NewLike
from comet.models import Product, ProductType, Favorite
from django.db.models import Count
from keystone.models import User
# Create your views here.
class newView(ListView):
    """
    全部新闻展示,只显示部分新闻内容
    """
    model = New
    template_name = 'meteor/all_news.html'
    context_object_name = 'news_list'

    def new(request):
        news_list = New.objects.all()
        return render(request, 'meteor/all_news.html', context={'news_list': news_list})


class newIndexShow(ListView):
    """
    首页新闻模块展示,最新十条新闻
    """
    model = New
    template_name = 'index.html'
    context_object_name = 'news_recently'

    def new_index_show(request):
        new_recently = New.objects.order_by('news_timestamp')
        return render(request, 'index.html', context={'new_recently': new_recently})


def new_detail(request, pk):
    """
    新闻详情页,根据news_id查询对应新闻详细信息并展示到详情页面
    :param news_id: 新闻ID
    :return:
    """
    new = get_object_or_404(New, pk=pk)

    return render(request, 'meteor/single_news.html', context={'new': new})


def new_like(request, news_id, user_id):
    """
    新闻点赞,获得对应新闻id并将点赞数增加1
    :param request:
    :param news_id:
    :param user_id:
    :return:
    """
    new = get_object_or_404(New,pk=news_id)
    user = get_object_or_404(User, pk=user_id)
    New.objects.filter(pk=news_id).update(new_like = new.news_like+1)
    NewLike.objects.get_or_create(news_title=new.news_title, news_id=new.news_id, user=user)

    return HttpResponseRedirect('/news')


class Index(ListView):

    def __init__(self):
        super(Index, self).__init__()
        self.model = ''
        self.context_object_name = ['hot_products', ]
        self.template_name = 'index.html'
        self.hot_products = []
        self.hot_news = []

    def index(self, request):
        self.hot_products.clear()
        try:
            # 获取所有类型产品的前10个
            sql_1 = 'SELECT * FROM comet_favorite cf WHERE cf.product_id IN ( SELECT product_id FROM comet_favorite GROUP BY product_id HAVING COUNT( product_id ) )'
            hot_products_id = Favorite.objects.raw(sql_1)[:3]
            for hpi in hot_products_id:
                overview_product = Product.objects.filter(product_id=hpi.product_id).all()[0]
                self.hot_products.append(overview_product)
            self.hot_news = New.objects.all()[:4]
        except:
            return render(request, '500.html')

        return render(request, self.template_name, {self.context_object_name[0]: self.hot_products, 'news_recently': self.hot_news})
